import axios from 'axios'
import { useCache } from 'vue-cache-optimization'

// 取消接口的方式 controller.abort()
let controller = new AbortController()

export const abort = () => {
  controller.abort()
  controller = new AbortController()
}

const instance = axios.create({
  baseURL: '/',
  timeout: 10000,
  headers: { 'X-Custom-Header': 'foobar' }
})

instance.interceptors.request.use(
  (config) => config,
  (error) => Promise.reject(error)
)

instance.interceptors.response.use(
  (response) => {
    // 打印接口返回结果
    const { url = '', method = '', params } = response.config
    const { data } = response
    console.groupCollapsed(`%c${method}: ${url}: ${JSON.stringify(params || {})}`, 'color: #4b4bc4')
    console.log('params', params)
    console.log('data', data)
    console.groupEnd()
    return response.data
  },
  (error) => Promise.reject(error)
)

export const request = (url, method, params, options) => {
  // 获取缓存数据 - start -
  const getCacheData = useCache({ url, method, params })
  const data = getCacheData(options?.cache || false)
  if (data) {
    return Promise.resolve(data)
  }
  // 获取缓存数据 - end -
  return instance({
    method,
    url,
    data: params,
    params,
    signal: controller.signal
  }).then((data) => {
    if (data && data.success) {
      // 设置缓存数据 - start -
      const setCacheData = useCache({ url, method, params, data })
      setCacheData(options?.cache || false)
      // 设置缓存数据 - end -
    }
    return data
  })
}

export const get = (url, params, options) => {
  return request(url, 'GET', params, options)
}

export const post = (url, params, options) => {
  return request(url, 'POST', params, options)
}
